﻿namespace ContactsSync.Providers.Outlook.Services
{
    using System;
    using System.IO;
    using System.Net;
    using Infrastructure;
    using Infrastructure.Models;
    using Microsoft.Practices.Composite.Events;

    public class ImageDownloader : IImageDownloader
    {
        public event EventHandler<DataEventArgs<ContactImage>> DownloadImageCompleted;

        public void DownloadImageAsync(Contact contact)
        {
            Uri uri; 
            if (contact.ImageSource != null && Uri.TryCreate(contact.ImageSource.ToString(), UriKind.Absolute, out uri))
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "GET";
                request.BeginGetResponse(
                    asyncResult =>
                        {
                            WebRequest req = (WebRequest) asyncResult.AsyncState;

                            HttpWebResponse response = (HttpWebResponse) req.EndGetResponse(asyncResult);

                            Stream stream = response.GetResponseStream();

                            this.OnDownloadImageCompleted(new ContactImage(contact.Id, stream));
                        },
                    request);
            }
            else
            {
                this.OnDownloadImageCompleted(null);
            }
        }

        private void OnDownloadImageCompleted(ContactImage contactImage)
        {
            EventHandler<DataEventArgs<ContactImage>> completed = this.DownloadImageCompleted;
            if (completed != null)
            {
                completed(this, new DataEventArgs<ContactImage>(contactImage));
            }
        }
    }
}